package com.vimi8.chick.plugins.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.media.MediaMetadataRetriever
import android.os.Environment
import android.os.SystemClock
import android.util.Base64
import com.eros.framework.constant.Constant.ImageConstants.BIGGESTWIDTH
import com.eros.framework.manager.impl.FileManager
import com.eros.framework.utils.ImageUtil
import okhttp3.ResponseBody
import java.io.*
import java.nio.ByteBuffer
import java.text.DecimalFormat

object FileUtil {

    /**
     * okhttp3 下载文件
     */
    fun writeFile(filePath: String, body: ResponseBody): File? {
        var inputStream: InputStream? = null
        var outputStream: FileOutputStream? = null
        var file: File? = null
        try {
            file = File(filePath)
            val dir = file.parentFile
            if (!dir.exists()) {
                dir.mkdirs()
            }

            //            val fileSize = body.contentLength()
            var downloadSize = 0
            val fileReader = ByteArray(4096)

            inputStream = body.byteStream()
            outputStream = FileOutputStream(file)

            loop@ while (true) {
                val read = inputStream.read(fileReader)
                if (read == -1) break@loop
                outputStream.write(fileReader, 0, read)
                downloadSize += read
            }

            outputStream.flush()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                inputStream?.close()
                outputStream?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return file
    }

    /**
     * 获取文件大小并格式化
     */
    fun formatFileSize(file: File): String {
        var fileSize = 0L
        var fileSizeString: String = "0B"
        var fis: FileInputStream? = null

        try {
            if (file.exists()) {
                fis = FileInputStream(file)
                fileSize = fis.available().toLong()
            }

            val df = DecimalFormat("#.00")
            fileSizeString = when (fileSize) {
                0L -> "0B"
                else -> {
                    when {
                        fileSize < 1024 -> df.format(fileSize.toDouble()) + "B"
                        fileSize < 1048576 -> df.format(fileSize.toDouble() / 1024) + "KB"
                        fileSize < 1073741824 -> df.format(fileSize.toDouble() / 1048576) + "MB"
                        else -> df.format(fileSize.toDouble() / 1073741824) + "GB"
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            fis?.close()
        }

        return fileSizeString
    }

    /**
     * 根据文件后缀名获得对应的MIME类型
     */
    fun getMimeType(filePath: String?): String {
        val mmr = MediaMetadataRetriever()
        var mime = "*/*"
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath)
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
            } catch (e: IllegalStateException) {
                return mime
            } catch (e: IllegalArgumentException) {
                return mime
            } catch (e: RuntimeException) {
                return mime
            }
        }
        return mime
    }

    /**
     * 获取根目录
     */
    fun getRootDir(): String {

        return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            Environment.getExternalStorageDirectory().absolutePath
        } else {
            ""
        }

    }

    /**
     * 可创建多个文件夹
     * dirPath 文件路径
     */
    fun mkDir(dirPath: String) {

        val dirArray = dirPath.split("/".toRegex())
        var pathTemp = ""
        for (i in 1 until dirArray.size) {
            pathTemp = "$pathTemp/${dirArray[i]}"
            val newF = File("${dirArray[0]}$pathTemp")
            if (!newF.exists()) {
                val cheatDir: Boolean = newF.mkdir()
                println(cheatDir)
            }
        }

    }

    /**
     * 创建文件
     *
     * dirpath 文件目录
     * fileName 文件名称
     */
    fun creatFile(dirPath: String = getRootDir(), fileName: String) {
        val file = File("$dirPath/$fileName")
        if (!file.exists()) {
            file.createNewFile()
        }

    }

    /**
     * 创建文件
     * filePath 文件路径
     */
    fun creatFile(filePath: String) {
        val file = File(filePath)
        if (!file.exists()) {
            file.createNewFile()
        }
    }

    /**
     * 创建文件
     * filePath 文件路径
     */
    fun creatFile(filePath: File) {
        if (!filePath.exists()) {
            filePath.createNewFile()
        }
    }

    /**
     * 删除文件
     *
     * dirpath 文件目录
     * fileName 文件名称
     */
    fun delFile(dirpath: String = getRootDir(), fileName: String): Boolean {
        val file = File("$dirpath/$fileName")
        if (file.checkFile()) {
            return false
        }
        return file.delete()
    }

    /**
     *  删除文件
     *  filepath 文件路径
     */
    fun delFile(filepath: File): Boolean {
        if (filepath.checkFile()) {
            return false
        }
        return filepath.delete()
    }

    /**
     *  删除文件
     *  filepath 文件路径
     */
    fun delFile(filepath: String): Boolean {
        val file = File(filepath)
        if (file.checkFile()) {
            return false
        }
        return file.delete()
    }


    /**
     * 删除文件夹
     * dirPath 文件路径
     */
    fun delDir(dirpath: String) {
        val dir = File(dirpath)
        deleteDirWihtFile(dir)
    }

    fun deleteDirWihtFile(dir: File?) {
        if (dir!!.checkFile())
            return
        for (file in dir.listFiles()) {
            if (file.isFile)
                file.delete() // 删除所有文件
            else if (file.isDirectory)
                deleteDirWihtFile(file) // 递规的方式删除文件夹
        }
        dir.delete() // 删除目录本身
    }

    private fun File.checkFile(): Boolean {
        return !this.exists() || !this.isDirectory
    }

    /**
     * 修改SD卡上的文件或目录名
     * oldFilePath 旧文件或文件夹路径
     * newFilePath 新文件或文件夹路径
     */
    fun renameFile(oldFilePath: String, newFilePath: String): Boolean {
        val oldFile = File(oldFilePath)
        val newFile = File(newFilePath)
        return oldFile.renameTo(newFile)
    }


    /**
     * 拷贝一个文件
     * srcFile源文件
     * destFile目标文件
     */
    @Throws(IOException::class)
    fun copyFileTo(srcFile: File, destFile: File): Boolean {
        return if (srcFile.isDirectory || destFile.isDirectory) {
            false
        } else {
            val fis = FileInputStream(srcFile)
            val fos = FileOutputStream(destFile)
            fis.copyTo(fos)
            fos.flush()
            closeIO(fos, fis)
            true
        }
    }

    /**
     *拷贝目录下的所有文件到指定目录
     * srcDir 原目录
     * destDir 目标目录
     */
    fun copyFilesTo(srcDir: File, destDir: File): Boolean {
        if (!srcDir.isDirectory || !destDir.isDirectory) return false // 判断是否是目录
        if (!destDir.exists()) return false // 判断目标目录是否存在
        val srcFiles = srcDir.listFiles()
        srcFiles.forEach {
            if (it.isFile) {
                val destFile = File("${destDir.path}/${it.name}")
                copyFileTo(it, destFile)
            } else {
                val theDestDir = File("${destDir.path}/${it.name}")
                copyFilesTo(it, theDestDir)
            }
        }

        return true
    }

    /**
     * 移动一个文件
     */
    fun moveFileTo(srcFile: File, destFile: File): Boolean {
        if (srcFile.isDirectory || destFile.isDirectory) return false
        val iscopy = copyFileTo(srcFile, destFile)
        return if (!iscopy) {
            false
        } else {
            delFile(srcFile)
            true
        }

    }

    /**
     * 移动目录下的所有文件到指定目录
     * srcDir 原路径
     * destDir 目标路径
     */
    @Throws(IOException::class)
    fun moveFilesTo(srcDir: File, destDir: File): Boolean {
        if (!srcDir.isDirectory or !destDir.isDirectory) {
            return false
        } else {
            val srcDirFiles = srcDir.listFiles()
            srcDirFiles.forEach {
                if (it.isFile) {
                    val oneDestFile = File("${destDir.path}/${it.name}")
                    moveFileTo(it, oneDestFile)
                    delFile(it)
                } else {
                    val oneDestFile = File(destDir.path + "//"
                        + it.name)
                    moveFilesTo(it, oneDestFile)
                    delDir(it.absolutePath)
                }

            }
            return true
        }

    }

    /**
     * 文件转byte数组
     * file 文件路径
     */
    @Throws(IOException::class)
    fun file2byte(file: File): ByteArray? {
        val inp = FileInputStream(file)
        val length = file.length().toInt()
        if (length > Integer.MAX_VALUE) { // 当文件的长度超过了int的最大值
            inp.close()
            return null
        }
        val bytes = inp.readBytes(length)
        closeIO(inp)
        return bytes
    }

    /**
     * 文件读取
     * filePath 文件路径
     */
    fun readFile(filePath: File): String? {
        if (!filePath.isFile) {
            return null
        } else {
            return filePath.readText()
        }
    }

    /**
     * 文件读取
     * strPath 文件路径
     */
    fun readFile(strPath: String): String? {
        return readFile(File(strPath))
    }

    /**
     * InputStream 转字符串
     */
    fun readInp(inp: InputStream): String? {
        val bytes: ByteArray = inp.readBytes()
        return String(bytes)
    }

    /**
     * BufferedReader 转字符串
     */
    fun readBuff(buff: BufferedReader): String? {
        return buff.readText()
    }

    /**
     * 写入数据
     */
    fun writeText(filePath: File, content: String) {
        creatFile(filePath)
        filePath.writeText(content)
    }

    /**
     * 追加数据
     */
    fun appendText(filePath: File, content: String) {
        creatFile(filePath)
        filePath.appendText(content)
    }

    /**
     * 追加数据
     */
    fun appendBytes(filePath: File, array: ByteArray) {
        creatFile(filePath)
        filePath.appendBytes(array)
    }

    /**
     * 获取文件大小
     */
    fun getLeng(filePath: File): Long {
        return if (!filePath.exists()) {
            -1
        } else {
            filePath.length()
        }
    }

    /**
     * 按时间排序
     */
    fun sortByTime(filePath: File): Array<File>? {
        if (!filePath.exists()) {
            return null
        }
        val files: Array<File> = filePath.listFiles()
        if (files.isEmpty()) {
            return null
        }
        files.sortBy { it.lastModified() }
        files.reverse()
        return files

    }

    /**
     * 关闭IO
     * @param closeables closeables
     */
    fun closeIO(vararg closeables: Closeable) {
        closeables
            .forEach {
                try {
                    it.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
    }

    /**
     * 得到视频缩略图
     */
    fun getVideoThumbnail(filePath: String): Bitmap? {
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
        try {
            retriever.setDataSource(filePath)
            bitmap = retriever.frameAtTime
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } catch (e: RuntimeException) {
            e.printStackTrace()
        } finally {
            try {
                retriever.release()
            } catch (e: RuntimeException) {
                e.printStackTrace()
            }
        }
        return bitmap
    }

    /**
     * Bitmap 转 ByteArray
     */
    fun getByteArrayFromBitmap(bitmap: Bitmap): ByteArray {
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)
        return baos.toByteArray()
        //        val buf = ByteBuffer.allocate(bitmap.byteCount)
        //        bitmap.copyPixelsToBuffer(buf)
        //        return buf.array()
    }

    /**
     * ByteArray 转 Bitmap
     * 这个方法生效的前提是，提供的 @param bitMapData 是包含了图像参数的，而非简单的RGBA数据
     */
    fun getBitmapFromByteArray(bitMapData: ByteArray): Bitmap {
        return BitmapFactory.decodeByteArray(bitMapData, 0, bitMapData.size)
    }

    /**
     * ByteArray 转 Bitmap
     * @param byteArray 仅仅是RGBA数据，需要传入 bitmap 的高宽等配置
     */
    fun getBitmapFromByteArray(byteArray: ByteArray, width: Int, height: Int, type: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap {
        val stitchBmp = Bitmap.createBitmap(width, height, type)
        stitchBmp.copyPixelsFromBuffer(ByteBuffer.wrap(byteArray))
        return stitchBmp
    }

    /**
     * 将图片转换成Base64编码的字符串
     */
    fun imageToBase64(imgFile: String): String? {
        if (imgFile.isEmpty()) return null

        var inputStream: InputStream? = null
        val data: ByteArray?
        var res: String? = null
        try {
            inputStream = FileInputStream(imgFile)
            data = ByteArray(inputStream.available())
            inputStream.read(data)
            res = Base64.encodeToString(data, Base64.DEFAULT)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inputStream?.close()
        }

        return res
    }

    fun saveBitmap(context: Context, bitmap: Bitmap?): String {
        val thumbFilePath = File(
            FileManager.getTempFilePath(context),
            SystemClock.currentThreadTimeMillis().toString()
        ).absolutePath + ".jpg"
        return ImageUtil.zoomImage(context, bitmap, 800, BIGGESTWIDTH, thumbFilePath)
    }

    fun assets2Drawable(context: Context, filePath: String?): Drawable? {
        if (filePath == null) {
            return null
        }
        var open : InputStream? = null
        var drawable: Drawable? = null
        try {
            open = context.assets.open(filePath)
            drawable = Drawable.createFromStream(open, null)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                open?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return drawable
    }
}
